package com.personalblog.service.serviceImpl;


import com.personalblog.handler.ApiNotFindException;
import com.personalblog.mapper.TagMapper;
import com.personalblog.po.Tag;
import com.personalblog.service.TagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

/**
 * @author jxau_scf
 * @date 2021/3/23 - 15:02
 */
@Service
public class TagServiceImpl implements TagService {
    private static final Logger logger = LoggerFactory.getLogger(TagServiceImpl.class);

    @Autowired
    private TagMapper tagMapper;


    @Override
    public int insertTag(Tag tag) {
        return tagMapper.insertTag(tag);
    }

    @Override
    public int deleteTag(int tagId) {
        return tagMapper.deleteTag(tagId);
    }

    @Override
    public int updateTag(int tagId, Tag tag) {
        Tag t = tagMapper.findTagById(tagId);
        if (t == null){
            logger.info("该标签不存在!");
            throw new ApiNotFindException("该标签不存在");
        }
        BeanUtils.copyProperties(tag,t);
        return tagMapper.updateTag(t);
    }

    @Override
    public Tag findTagById(int tagId) {
        return tagMapper.findTagById(tagId);
    }

    @Override
    public Tag findTagByName(String tagName) {
        return tagMapper.findTagByName(tagName);
    }

    @Override
    public List<Tag> findTags() {
        return tagMapper.findTags();
    }

    @Override
    public List<Tag> findTagListByIds(String Ids) {
        return tagMapper.findTagListByIds(convertToList(Ids));
    }

    @Override
    public List<Tag> findTagsFetchBlogs() {
        return tagMapper.findTagsFetchBlogs();
    }

    private List<Integer> convertToList(String ids){
        List<Integer> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null){
            String[] idarray = ids.split(",");
            for (int i=0;i<idarray.length;i++){
                list.add(new Integer(idarray[i]));
            }
        }
        return list;
    }
}
